from typing import Any, List
from fastapi import APIRouter, Depends, HTTPException, UploadFile, File
from sqlalchemy.orm import Session
from pathlib import Path

from app.api import deps
from app.schemas import workarea as schemas
from app.database.models.erp import WorkArea
from app.database.models.base import User

router = APIRouter()

# 获取项目根目录的绝对路径
BASE_DIR = Path(__file__).resolve().parent.parent.parent.parent
IMAGES_DIR = BASE_DIR / "images"

@router.get("/", response_model=List[schemas.WorkArea])
def list_workareas(
    db: Session = Depends(deps.get_db),
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """获取工作区列表"""
    try:
        if current_user.role == "admin":
            return db.query(WorkArea).all()
        return [db.query(WorkArea).filter(WorkArea.ID == current_user.workarea_id).first()]
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/", response_model=schemas.WorkArea)
def create_workarea(
    *,
    db: Session = Depends(deps.get_db),
    workarea_in: schemas.WorkAreaCreate,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """创建新工作区"""
    if current_user.role != "admin":
        raise HTTPException(status_code=403, detail="Not enough permissions")
    
    try:
        workarea = WorkArea(**workarea_in.dict())
        db.add(workarea)
        db.commit()
        db.refresh(workarea)
        return workarea
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/{workarea_id}", response_model=schemas.WorkArea)
async def get_workarea(
    workarea_id: int,
    db: Session = Depends(deps.get_db),
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """获取工作区信息"""
    try:
        # 检查用户权限
        if current_user.role != "admin" and current_user.workarea_id != workarea_id:
            raise HTTPException(
                status_code=403,
                detail="No permission to access this workarea"
            )

        workarea = db.query(WorkArea).filter(WorkArea.ID == workarea_id).first()
        if not workarea:
            raise HTTPException(status_code=404, detail="WorkArea not found")

        return workarea
    except HTTPException as he:
        raise he
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"Error retrieving workarea: {str(e)}"
        )

@router.put("/{workarea_id}", response_model=schemas.WorkArea)
def update_workarea(
    *,
    db: Session = Depends(deps.get_db),
    workarea_id: int,
    workarea_in: schemas.WorkAreaUpdate,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """更新工作区"""
    if current_user.role != "admin":
        raise HTTPException(status_code=403, detail="Not enough permissions")
    
    try:
        workarea = db.query(WorkArea).filter(WorkArea.ID == workarea_id).first()
        if not workarea:
            raise HTTPException(status_code=404, detail="WorkArea not found")
        
        for field, value in workarea_in.dict(exclude_unset=True).items():
            setattr(workarea, field, value)
        
        db.add(workarea)
        db.commit()
        db.refresh(workarea)
        return workarea
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=str(e))

@router.delete("/{workarea_id}")
def delete_workarea(
    *,
    db: Session = Depends(deps.get_db),
    workarea_id: int,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """删除工作区"""
    if current_user.role != "admin":
        raise HTTPException(status_code=403, detail="Not enough permissions")
    
    workarea = db.query(WorkArea).filter(WorkArea.ID == workarea_id).first()
    if not workarea:
        raise HTTPException(status_code=404, detail="WorkArea not found")
    
    # 检查是否有关联的用户
    if db.query(User).filter(User.workarea_id == workarea_id).first():
        raise HTTPException(
            status_code=400,
            detail="Cannot delete workarea with associated users"
        )
    
    db.delete(workarea)
    db.commit()
    return {"ok": True}

@router.post("/logo")
async def upload_workarea_logo(
    *,
    db: Session = Depends(deps.get_db),
    current_user: User = Depends(deps.get_current_active_user),
    file: UploadFile = File(...)
) -> Any:
    """上传工作区Logo"""
    try:
        # 检查用户是否有权限（必须是agent或admin）
        if current_user.role not in ["admin", "agent"]:
            raise HTTPException(status_code=403, detail="Not enough permissions")

        # 检查文件类型
        if not file.content_type.startswith("image/"):
            raise HTTPException(status_code=400, detail="File must be an image")

        # 确保images目录存在
        IMAGES_DIR.mkdir(exist_ok=True)

        # 构建文件名
        filename = f"workarea_logo_{current_user.workarea_id}.png"
        file_path = IMAGES_DIR / filename

        # 保存文件
        content = await file.read()
        with open(file_path, "wb") as f:
            f.write(content)

        # 更新数据库中的URL
        workarea = db.query(WorkArea).filter(
            WorkArea.ID == current_user.workarea_id
        ).first()
        
        if not workarea:
            raise HTTPException(status_code=404, detail="WorkArea not found")

        # 更新PDFLogoUrl（存储相对路径）
        workarea.PDFLogoUrl = f"/images/{filename}"
        db.commit()

        return {
            "message": "Logo uploaded successfully",
            "filename": filename,
            "url": f"/images/{filename}"
        }

    except HTTPException as he:
        raise he
    except Exception as e:
        db.rollback()
        raise HTTPException(
            status_code=500,
            detail=f"Error uploading logo: {str(e)}"
        ) 